package com.ruoyi.security.service.backtest.gridtrading.processor.impl;

import com.ruoyi.security.service.backtest.gridtrading.context.BacktestContext;
import com.ruoyi.security.service.backtest.gridtrading.processor.AbstractTradeProcessor;
import org.springframework.stereotype.Component;

/**
 * @author yeoman
 * @date 2025/11/7 23:44
 * @description
 */
@Component("buyTradeProcessor")
public class BuyTradeProcessor extends AbstractTradeProcessor {
    @Override
    protected void updateContext(BacktestContext context) {
        BacktestContext.BacktestVariable backtestVariable = context.getBacktestVariable();
        BacktestContext.BacktestVariable.TradeInfo tradeInfo = backtestVariable.getTradeInfo();
        BacktestContext.BacktestVariable.DayTradeInfo.Buy dayTradeInfoBuy = backtestVariable.getDayTradeInfo().getBuy();
        BacktestContext.BacktestVariable.TotalTradeInfo.Buy totalTradeInfoBuy = backtestVariable.getTotalTradeInfo().getBuy();

        // 更新当前持仓
        backtestVariable.setPosition(backtestVariable.getPosition() + tradeInfo.getTradeQuantity());
        // 更新可用资金
        if (backtestVariable.getAvailableAmount() != null) {
            backtestVariable.setAvailableAmount(backtestVariable.getAvailableAmount().subtract(tradeInfo.getTradeAmount()));
        }

        /*更新当日信息*/
        // 更新当日买入次数
        dayTradeInfoBuy.setDayBuyCount(dayTradeInfoBuy.getDayBuyCount() + 1);
        // 更新当日买入数量
        dayTradeInfoBuy.setDayBuyQuantity(dayTradeInfoBuy.getDayBuyQuantity() + tradeInfo.getTradeQuantity());
        // 更新当日买入金额
        dayTradeInfoBuy.setDayBuyAmount(dayTradeInfoBuy.getDayBuyAmount().add(tradeInfo.getTradeAmount()));
        // 更新当日买入手续费
        dayTradeInfoBuy.setDayBuyChargeAmount(dayTradeInfoBuy.getDayBuyChargeAmount().add(tradeInfo.getTradeChargeAmount()));

        /*更新总信息*/
        // 更新总的买入次数
        totalTradeInfoBuy.setTotalBuyCount(totalTradeInfoBuy.getTotalBuyCount() + 1);
        // 更新总的买入数量
        totalTradeInfoBuy.setTotalBuyQuantity(totalTradeInfoBuy.getTotalBuyQuantity() + tradeInfo.getTradeQuantity());
        // 更新总的买入金额
        totalTradeInfoBuy.setTotalBuyAmount(totalTradeInfoBuy.getTotalBuyAmount().add(tradeInfo.getTradeAmount()));
        // 更新总的买入手续费
        totalTradeInfoBuy.setTotalBuyChargeAmount(totalTradeInfoBuy.getTotalBuyChargeAmount().add(tradeInfo.getTradeChargeAmount()));

        // 更新当前投入资金
        backtestVariable.setInvestmentAmount(backtestVariable.getInvestmentAmount().add(tradeInfo.getTradeAmount()));
        // 更新最大投入资金
        backtestVariable.setMaxInvestmentAmount(backtestVariable.getMaxInvestmentAmount().max(backtestVariable.getInvestmentAmount()));
    }
}
